/*
 *  This class is part of WorkTimeCalculator Android App
 *  Author: Domenico Pio Novelli
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.dpndeveloper.wtc.dialogs;

import java.util.Calendar;
import java.util.TimeZone;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;

import com.dpndeveloper.wtc.R;
import com.dpndeveloper.wtc.dataprovider.WtcInterval;
import com.dpndeveloper.wtc.dataprovider.WtcIntervalDataBaseHelper;
import com.dpndeveloper.wtc.listener.OnIntervalSetEvent;
import com.dpndeveloper.wtc.listener.OnIntervalSetListener;

/**
 * Dialog to show/modify an Interval
 * 
 * @author Domenico Pio Novelli
 * 
 */
public class IntervalDialog extends AlertDialog implements
		OnTimeChangedListener {

	/* Interval to show/modify */
	private WtcInterval					m_initialInterval;

	/* the layout view of the dialog */
	private View						m_view;

	/* Instance of DatabaseHelper to manage WtcIntervals */
	private WtcIntervalDataBaseHelper	m_databaseHelper;

	private OnIntervalSetListener		m_onIntervalSetListener;

	private boolean						m_onlyStart;

	/**
	 * Constructor
	 * 
	 * @param context
	 *            The context where the View associated with this Dialog is
	 *            running
	 * @param initialInterval
	 *            the related interval
	 * @param onIntervalSetListener
	 *            an OnIntervalSetListener
	 * @param databaseHelper
	 *            Instance of DatabaseHelper to manage WtcIntervals
	 * @param onlyStart
	 *            true if dialog have to set only start time, false otherwise
	 */
	public IntervalDialog(Context context, WtcInterval initialInterval,
			OnIntervalSetListener onIntervalSetListener,
			WtcIntervalDataBaseHelper databaseHelper, boolean onlyStart) {
		super(context);
		this.m_initialInterval = initialInterval;
		this.m_databaseHelper = databaseHelper;
		this.m_onIntervalSetListener = onIntervalSetListener;
		this.m_onlyStart = onlyStart;
		setTitle(R.string.workInterval);

		m_view = getLayoutInflater().inflate(R.layout.interval_layout, null);
		setView(m_view);

		setButton(DialogInterface.BUTTON_POSITIVE,
				context.getText(R.string.ok),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						onOkPressed();
						dismiss();
					}

				});

		setButton(DialogInterface.BUTTON_NEGATIVE,
				context.getText(R.string.close),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dismiss();
					}

				});

		updateTimePickers();

		getStartPicker().setOnTimeChangedListener(this);
		getStopPicker().setOnTimeChangedListener(this);

		setCancelable(true);
		setIcon(R.drawable.ic_launcher);

		if (onlyStart) {
			LinearLayout layoutStartAt = (LinearLayout) getView().findViewById(
					R.id.layoutStopAt);
			layoutStartAt.getLayoutParams().height = 0;
		}

	}

	/**
	 * Set the interval to use in the dialog
	 * 
	 * @param initialInterval
	 */
	public void setWtcInterval(WtcInterval initialInterval) {
		this.m_initialInterval = initialInterval;
	}

	@Override
	public void onTimeChanged(TimePicker arg0, int arg1, int arg2) {
		// update ok Button
		getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(isValid());
	}

	/**
	 * Validate the values of start and end time
	 * 
	 * @return true if times are valid, false otherwise
	 */
	protected boolean isValid() {
		int startHourOfDay = getStartPicker().getCurrentHour();
		int startMinute = getStartPicker().getCurrentMinute();
		int endHourOfDay = getStopPicker().getCurrentHour();
		int endMinute = getStopPicker().getCurrentMinute();

		// If the set end time is before the last start time
		return !(startHourOfDay > endHourOfDay || (startHourOfDay == endHourOfDay && startMinute >= endMinute));
	}

	/**
	 * Return the interval used in the dialog
	 * 
	 * @return the interval
	 */
	protected WtcInterval getInitialInterval() {
		return m_initialInterval;
	}

	/**
	 * Return the time Picker for end time
	 * 
	 * @return time picker for end time
	 */
	protected TimePicker getStopPicker() {
		TimePicker timepickerStop = (TimePicker) m_view
				.findViewById(R.id.timePickerStopAt);
		return timepickerStop;
	}

	/**
	 * Return the time Picker for start time
	 * 
	 * @return time picker for start time
	 */
	protected TimePicker getStartPicker() {
		TimePicker timepickerStart = (TimePicker) m_view
				.findViewById(R.id.timePickerStartAt);
		return timepickerStart;
	}

	/**
	 * Return the Edit Text for description
	 * 
	 * @return Edit Text for description
	 */
	protected EditText getDescriptionTextView() {
		EditText descriptionText = (EditText) m_view
				.findViewById(R.id.editTextDescription);
		return descriptionText;
	}

	@Override
	protected void onStart() {
		super.onStart();
		updateTimePickers();
	}

	/**
	 * Return the Layout View of the dialog
	 * 
	 * @return the Layout View of the dialog
	 */
	protected View getView() {
		return m_view;
	}

	/**
	 * Method executed when Ok Button is pressed.
	 */
	protected void onOkPressed() {

		WtcInterval interval = m_initialInterval;
		// if there isn't an initial interval
		if (interval == null) {
			interval = new WtcInterval();
			interval.setStartTime(Calendar.getInstance(TimeZone.getDefault()));
		}
		Calendar time = interval.getStartTime();
		// set the start time from picker
		time.set(Calendar.HOUR_OF_DAY, getStartPicker().getCurrentHour()
				.intValue());
		time.set(Calendar.MINUTE, getStartPicker().getCurrentMinute()
				.intValue());
		time.set(Calendar.SECOND, 0);
		time.set(Calendar.MILLISECOND, 0);
		interval.setStartTime(time);

		if (!m_onlyStart) {
			Calendar endTime = Calendar.getInstance(TimeZone.getDefault());
			if (m_initialInterval.getEndTime() != null) {
				endTime = m_initialInterval.getEndTime();
			} else {
				endTime = Calendar.getInstance(TimeZone.getDefault());
				endTime.setTime(interval.getStartTime().getTime());
			}
			// set the end time from picker
			endTime.set(Calendar.HOUR_OF_DAY, getStopPicker().getCurrentHour()
					.intValue());
			endTime.set(Calendar.MINUTE, getStopPicker().getCurrentMinute()
					.intValue());
			endTime.set(Calendar.SECOND, 0);
			endTime.set(Calendar.MILLISECOND, 0);
			interval.setEndTime(endTime);
		}

		interval.setDescription(getDescriptionTextView().getText().toString());

		if (m_initialInterval != null && m_initialInterval.getId() != null) {
			// Update the interval
			Log.v("onIntervalSet - EndAt", "update Interval");
			m_databaseHelper.update(interval);
		} else {
			m_databaseHelper.insert(interval);
		}

		// notifies the event
		OnIntervalSetEvent event = new OnIntervalSetEvent(this, interval);
		m_onIntervalSetListener.onIntervalSet(event);
	}

	/**
	 * update the content of time Pickers in dialog (start and end times)
	 */
	private void updateTimePickers() {

		Calendar now = Calendar.getInstance(TimeZone.getDefault());
		Calendar startTime = now;
		Calendar stopTime = now;

		TimePicker timepickerStart = getStartPicker();
		timepickerStart.setIs24HourView(true);
		if (m_initialInterval != null
				&& m_initialInterval.getStartTime() != null) {
			startTime = m_initialInterval.getStartTime();
		}
		timepickerStart.setCurrentHour(startTime.get(Calendar.HOUR_OF_DAY));
		timepickerStart.setCurrentMinute(startTime.get(Calendar.MINUTE));

		TimePicker timepickerStop = getStopPicker();
		timepickerStop.setIs24HourView(true);
		if (m_initialInterval != null && m_initialInterval.getEndTime() != null) {
			stopTime = m_initialInterval.getEndTime();
		}
		timepickerStop.setCurrentHour(stopTime.get(Calendar.HOUR_OF_DAY));
		timepickerStop.setCurrentMinute(stopTime.get(Calendar.MINUTE));

		if (m_initialInterval != null
				&& m_initialInterval.getDescription() != null) {
			getDescriptionTextView()
					.setText(m_initialInterval.getDescription());
		}
	}

}
